package com.jackrain.nea.common;

import com.alibaba.fastjson.JSONArray;

/**
 * 字符串操作通用类
 *
 * @author Yvan
 */
public class StringUtils {

    /**
     * 判断当前字符串是否为纯数字
     *
     * @param str 元字符串
     */
    public static boolean isNumeric(String str) {
        for (int i = 0; i < str.length(); i++) {
            if (!Character.isDigit(str.charAt(i))) {
                return false;
            }
        }
        return true;
    }

    /**
     * 替换当前字符串中的"."为"_"，如果当前为主表字段则直接截取尾部字段(demo:a.b => a_b)
     *
     * @param source    字符串源
     * @param tableName 主表名称
     */
    public static String getReplacePointToUnderLine(String source, String tableName) {
        if (source.startsWith(tableName)) {
            return source.substring(tableName.length() + 1, source.length());
        }
        return source.replace(".", "_");
    }

    /**
     * 获取替换"."为"_"得SQL字符串(demo: a.b => a.b as a_b)
     *
     * @param array     字符串源JSON数组
     * @param tableName 目标表名
     */
    public static String getSQLStringReplacePointToUnderLine(JSONArray array, String tableName) {
        StringBuffer res = new StringBuffer();
        if (array != null && array.size() > 0) {
            for (Object o : array) {
                res.append(o.toString() + " as " + getReplacePointToUnderLine(o.toString(), tableName) + ", ");
            }
        }
        if (res != null && res.length() > 0) {
            // 去除尾巴多余的", "
            return res.toString().substring(0, (res.length() - 2));
        }
        return null;
    }

    /**
     * 获取替换斜杠后的数据(/或者\)(demo: a/b => ["a","b"] 或 a\b => ["a","b"])
     *
     * @param path 带截取路径
     */
    public static String[] getSpitListBySlant(String path) {
        if (path == null) {
            return null;
        }
        // 存在反斜杠状态下以反斜杠截取
        if (path.lastIndexOf("/") > 0) {
            return path.split("/");
        }
        return path.split("\\\\");
    }

    /**
     * 截取最后一个"_"前面的数据
     *
     * @param source 元字符串
     */
    public static String getSpiltLastUnderLine(String source) {
        if (source != null) {
            int index = source.lastIndexOf("_");
            if (index > 0) {
                return source.substring(0, index);
            }else{
                return source;
            }
        }
        return null;
    }

    /**
     * 根据"."截取
     * @param source 元数据
     */
    public static String[] getSpiltByPoint(String source){
        if(source != null && source.length() > 0){
            return source.split("\\.");
        }
        return null;
    }
}
